/**
 * Created by MaoXP on 2016/4/5.
 */

$(function () {

    //初始化加载成员列表
    initPage();

    //member item 绑定事件
    browserRedirect();
    //显示添加成员窗口及操作
    var currentRole = '';
    $('.add-member-item').click(function () {
        getFriendsList();
        $('#search-member').val('');
        var $addMemberDiv = $('#add-member');
        var $addCompeteBtn = $('#add-complete');
        currentRole = $(this).attr('data-member-role');
        if(!$addCompeteBtn.hasClass('disabled')){
            $addCompeteBtn.addClass('disabled');
        }
        $addMemberDiv.modal('show');
    });
    //选择成员
    $('.outer').delegate('.add-member-list-info','click',function () {//点击事件===
        $(this).prev().find('input[type="checkbox"]').click();
    });
    //确定按钮是否disable
    $('.outer').on('change','input[type="checkbox"]',function () {//判断有选择的项
        if($(this).is(':checked')){//如果选中，父元素给属性checked
            $(this).parents('.add-member-list-item').addClass('checked');
        }else{
            $(this).parents('.add-member-list-item').removeClass('checked');
        };
        var $addMemberDiv=$('#add-member');
        var $addCompeteBtn = $('#add-complete');
        var isChecked = $addMemberDiv.find('input[type="checkbox"]').is(':checked');//判断是否有选中的
        if (isChecked) {
            $addCompeteBtn.removeClass('disabled');
        } else {
            $addCompeteBtn.addClass('disabled');
        };
    });
    //筛选成员
    $('#search-member').on('change keyup',function () {
        var keyword = $(this).val().trim();
        if(keyword == ''){
            $('.add-member-list-item').show();
            return;
        }
        var doctorList = $('.add-member-list-item .doctor-name');
        for(var i =0;i<doctorList.length;i++){
            if(doctorList[i].innerText.indexOf(keyword) < 0){
                $('.add-member-list-item').eq(i).hide();
            }else{
                $('.add-member-list-item').eq(i).show();
            }
        }
        if(keyword.length == 11 && typeof Number(keyword) == 'number'){
            // $('.add-member-list .form-group .invite').remove();
            // var $html = $(createFriendsDom());
            // $html.addClass('invite').find('.doctor-name').text(keyword);
            // $html.addClass('invite').find('.doctor-info').text('邀请加入');
            // $('.add-member-list .form-group').append($html);
            // $.material.init();
        }else{
            $('.add-member-list .form-group .invite').remove();
        }
    });
    //点击确定按钮添加成员
    $('#add-complete').click(function() {
        if ($(this).hasClass('disabled')) return false;
        var choiceListDom = $('.add-member-list .add-member-list-item.checked');
        var members = [];
        for (var i = 0; i < choiceListDom.length; i++) {
            var currentDom = $(choiceListDom[i]);
            var doctoruserid = currentDom.attr('id');
            if(doctoruserid && isExistMember(doctoruserid)) continue;
            members.push({
                "doctor": doctoruserid,
                "doctorname": currentDom.find(".doctor-name").text(),
                "role": currentRole
            });
        }
        if(members.length){
            new followupPlan().addGroupMembers(members,function (res, status) {
                res = JSON.parse(res);
                if(res.code == '000'){
                    $$.modal.tips('添加成功',1500);
                    var resData=JSON.parse(res.data);
                    var memberData=resData.members;
                    for (var i = 0; i < members.length; i++) {
                        var $html = $(createMemberDom());
                        $html.first().attr('id', members[i].doctor);
                        $html.find('.user-avatar').html('<img src="'+ urlParam.basePictureUrl + memberData[i].photo +'">');
                        var $memberItemSpan = $html.first().find('.member-item').find('li').last().find('span');
                        $memberItemSpan.first().html(members[i].doctorname);
                        var $memberInfoLi = $html.first().find('.member-info').find('li');
                        $memberInfoLi.first().find('span').html(memberData[i].hospital);
                        $memberInfoLi.eq(1).find('span').html(memberData[i].subDept);
                        $memberInfoLi.last().find('span').html(memberData[i].title);
                        if (members[i].role == 'admin') {
                            $memberItemSpan.last().html('管理员').attr('data-role','admin');
                            $('.member-wrapper:first > div.row').append($html);
                        }else{
                            $memberItemSpan.last().html('成员').attr('data-role','member');
                            $('.member-wrapper:last > div.row').append($html);
                        }
                    }
                }
            });
        }
    });
    //删除成员
    $('.outer').on('click','.close-member-item-wrapper',function() {
        var dom = $(this);
        var $memberItemDiv = dom.parent();
        var $memberInfoDiv = dom.parent().next();
        $$.modal.confirm('删除成员后，他将不能再登录平台开展随访工作。<br>确定要删除该成员吗？','不，再想想','删除',function () {
            new followupPlan().removeGroupMembers([{
                "doctor": dom.parents('.member-item-wrapper').attr('id')
            }],function (res) {
                res = JSON.parse(res);
                if(res.code == '000'){
                    $$.modal.tips('移除成功',1500);
                    dom.parent().parent().remove();
                }
            });
        });
        $memberInfoDiv.hide();
        $memberItemDiv.parent().attr('data-show', '0');
        dom.parent().css({
            'border-bottom-left-radius': '2px',
            'border-bottom-right-radius': '2px'
        });
        dom.hide();
    });

    //窗口变化时重新计算member info div 的 width
    $(window).resize(function () {
        var $memberInfoDiv = $('.member-info');
        //setMemberInfoDivWidth($memberInfoDiv);
        var contentWidth = parseInt($memberInfoDiv.parent().width())- 15 * 2;
        //dom.show();
        $memberInfoDiv.width(contentWidth);
    });
});

//设置member-info div 的width
function setMemberInfoDivWidth(dom) {
    var contentWidth = parseInt(dom.parent().width()) - 15 * 2;
    dom.show();
    dom.width(contentWidth);
}

//设置member-info div 的 position: top
function setMemberPosTop(dom) {
    if (dom.length == 0) {
        return;
    }
    var contentHeight = parseInt(dom.parent().height()) - 18;
    dom.css('top', contentHeight + 'px');
}

//判断是否是移动设备
function browserRedirect() {
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    var bIsAndroid = sUserAgent.match(/android/i) == "android";
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
        //设置member item 的点击事件，show/hide member info
        $('.outer').on('click','.member-item',
            function () {
                var $memberInfoDiv = $(this).next('.member-info');
                var $memberItemDiv = $(this);
                var $memberItemDivs = $('.member-item');
                var $closeBtn = $(this).find('.close-member-item-wrapper');
                var flag = $memberItemDiv.parent().attr('data-show');
                $('.member-info').hide();
                $('.close-member-item-wrapper').hide();
                $memberItemDivs.parent().attr('data-show', '0');
                setMemberPosTop($memberInfoDiv);
                if (flag == '0') {
                    setMemberInfoDivWidth($memberInfoDiv);
                    $memberItemDiv.parent().attr('data-show', '1');
                    $memberItemDiv.css({
                        'border-bottom-left-radius': '0',
                        'border-bottom-right-radius': '0'
                    });
                    $closeBtn.show();
                } else {
                    $memberInfoDiv.hide();
                    $memberItemDiv.parent().attr('data-show', '0');
                    $memberItemDiv.css({
                        'border-bottom-left-radius': '2px',
                        'border-bottom-right-radius': '2px'
                    });
                    $closeBtn.hide();
                }
            }
        );
    } else {
        //设置member item 的hover事件，show/hide member info
        $('.outer').on('mouseover','.member-item',
            function() {
                var $memberInfoDiv = $(this).next('.member-info');
                var $memberItemDiv = $(this);
                var $memberItemDivs = $('.member-item');
                var $closeBtn = $(this).find('.close-member-item-wrapper');
                var flag = $memberItemDiv.parent().attr('data-show');
                $('.member-info').hide();
                $('.close-member-item-wrapper').hide();
                $memberItemDivs.parent().attr('data-show', '0');
                setMemberPosTop($memberInfoDiv);
                if (flag == '0') {
                    setMemberInfoDivWidth($memberInfoDiv);
                    $memberItemDiv.parent().attr('data-show', '1');
                    $memberItemDiv.css({
                        'border-bottom-left-radius': '0',
                        'border-bottom-right-radius': '0'
                    });
                    $closeBtn.show();
                }
            });
        $('.outer').on('mouseout','.member-item',
            function () {
                var $memberInfoDiv = $(this).next('.member-info');
                var $memberItemDiv = $(this);
                var $memberItemDivs = $('.member-item');
                var $closeBtn = $(this).find('.close-member-item-wrapper');
                var flag = $memberItemDiv.parent().attr('data-show');
                $('.member-info').hide();
                $('.close-member-item-wrapper').hide();
                $memberItemDivs.parent().attr('data-show', '0');
                setMemberPosTop($memberInfoDiv);
                if (flag == '1') {
                    $memberInfoDiv.hide();
                    $memberItemDiv.parent().attr('data-show', '0');
                    $memberItemDiv.css({
                        'border-bottom-left-radius': '2px',
                        'border-bottom-right-radius': '2px'
                    });
                    $closeBtn.hide();
                }
        });
    }
}

//add member dom
function createMemberDom() {
    var html = '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 member-item-wrapper here" data-show="0">' +
        '<div class="member-item">' +
        '<i class="material-icons close-member-item-wrapper">&#xE5CD;</i>' +
        '<ul>' +
        '<li class="col-md-4 col-sm-5 col-xs-5">' +
        '<span class="blue-round-head text-center user-avatar"><i class="material-icons">&#xE7FD;</i></span>' +
        '</li>' +
        '<li class="col-md-8 col-sm-7 col-xs-7"><span class="doctor-name"></span><span class="gray"></span></li>' +
        '</ul></div>' +
        '<div class="well member-info">' +
        '<ul>' +
        '<li><i class="material-icons">&#xE7EE;</i><span class="gray"></span></li>' +
        '<li><i class="material-icons">&#xE563;</i><span class="gray"></span></li>' +
        '<li><i class="material-icons">&#xE7FD;</i><span class="gray"></span></li>' +
        '</ul></div></div>';
    return html;
}

//add friends list item dom
function createFriendsDom() {
    var html = '<div class="add-member-list-item">' +
        '<div class="checkbox">' +
        '<label><input type="checkbox"></label></div>' +
        '<div class="add-member-list-info">' +
        '<ul><li class="add-member-head">' +
        '<span class="blue-round-head text-center">' +
        '<i class="material-icons">&#xE7FD;</i></span></li>' +
        '<li class="add-member-info">' +
        '<span class="doctor-name"></span><br>' +
        '<span class="gray doctor-info"></span></li></ul></div></div>';
    return html;
}

//判断页面是否已经存在指定的医生
function isExistMember(doctorId) {
    var flag = false;
    $('.member-item-wrapper').each(function() {
        if ($(this).attr('id') == doctorId) {
            flag = true;
            return false;
        }
    });
    return flag;
}

//页面初始化是加载成员列表
function initPage() {
    new followupPlan().getGroupMembers(function (res, status) {
        res = JSON.parse(res);
        if(res.code == '000'){
            var resData = JSON.parse(res.data);
            var member = resData.members;
            for (var i = 0; i < member.length; i++) {
                var $html = $(createMemberDom());
                if(member[i].photo){//如果有照片的时候
                    $html.find('.blue-round-head').html('<img data-src="'+ member[i].photo +'" src="'+ urlParam.basePictureUrl + member[i].photo +'">');
                }
                $html.first().attr('id', member[i].doctor);
                var $memberItemSpan = $html.first().find('.member-item').find('li').last().find('span');
                $memberItemSpan.first().html(member[i].doctorname);
                var $memberInfoLi = $html.first().find('.member-info').find('li');
                $memberInfoLi.first().find('span').html(member[i].hospital);
                $memberInfoLi.eq(1).find('span').html(member[i].subDept);
                $memberInfoLi.last().find('span').html(member[i].title);
                if (member[i].role == 'admin') {
                    $memberItemSpan.last().html('管理员').attr('data-role','admin');
                    $('.member-wrapper:first > div.row').append($html);
                }else{
                    $memberItemSpan.last().html('成员').attr('data-role','member');
                    $('.member-wrapper:last > div.row').append($html);
                }
            }
            $('.outer').addClass('active');
        }
    });
}
//获取成员关系列表
function getFriendsList() {
    new followupPlan().getDoctorFriends(function (res,status) {
        res = JSON.parse(res);
        if(res.code == '000'){
            var friends = JSON.parse(res.data);
            var listArray = [];
            friends.sort(function(a,b){return a.name.localeCompare(b.name)});
            for (var i = 0; i < friends.length; i++) {
                var $html = $(createFriendsDom());
                if(friends[i].photo){
                    $html.find('.blue-round-head').html('<img data-src="'+ friends[i].photo +'" src="'+ urlParam.basePictureUrl + friends[i].photo +'">');
                }
                $html.attr('id', friends[i].doctoruserid);
                $html.find('.doctor-name').html(friends[i].name).attr('data-title',friends[i].title);
                var deptHosp = friends[i].deptname + '，' + friends[i].hospname;
                if ($(window).width() <= 360) {
                    deptHosp = deptHosp.slice(0, 14) + '...';
                }
                $html.find('.gray').html(deptHosp).attr({'title':friends[i].deptname + '，' + friends[i].hospname,'data-deptname':friends[i].deptname,'data-hospname':friends[i].hospname});
                listArray.push($html.prop('outerHTML'));
            }
            $('.add-member-list .form-group').html((listArray.join('') || '<span class="empty-tips">好友列表为空</span>'));
            $.material.init();
        }
    });
}
